package com.meteor.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fhs.trans.service.impl.TransService;
import com.meteor.api.feign.newFeign.NewFeign;
import com.meteor.api.feign.newFeign.dto.CommunityDTO;
import com.meteor.api.feign.param.CommunityParam;
import com.meteor.api.feign.param.UserParam;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.user.convert.SysMerchantConvert;
import com.meteor.user.entity.SysMerchant;
import com.meteor.user.entity.SysUser;
import com.meteor.user.mapper.SysRoleMapper;
import com.meteor.user.service.*;
import com.meteor.user.vo.SysMerchantVO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.excel.ExcelFinishCallBack;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.DateUtils;
import com.meteor.framework.common.utils.ExcelUtils;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.user.convert.SysUserConvert;
import com.meteor.user.mapper.SysUserMapper;
import com.meteor.user.enums.SuperAdminEnum;
import com.meteor.user.query.SysRoleUserQuery;
import com.meteor.user.query.SysUserQuery;
import com.meteor.user.vo.SysUserExcelVO;
import com.meteor.user.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @author lynn
 * @date 2024/1/03
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserRoleService sysUserRoleService;
    private final SysUserPostService sysUserPostService;
    private final SysUserTokenService sysUserTokenService;
    private final TransService transService;
    private final NewFeign newFeign;
    private final SysRoleMapper sysRoleMapper;
    private final SysOrgService sysOrgService;

    @Override
    public PageResult<SysUserVO> page(SysUserQuery query) {

        if(!ObjectUtils.isEmpty(query.getOrgId())){
            query.setOrgIds(sysOrgService.getSubOrgIdList(query.getOrgId()));
        }

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<SysUser> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<SysUser> list = baseMapper.getList(params);

        Map<String,String> communityMap = new HashMap<>();
        if(!ObjectUtils.isEmpty(list)){
            CommunityParam param = new CommunityParam();
            param.setIds(list.stream().map(t->t.getCommunityId()).collect(Collectors.toList()));
//            ResponseData responseData = JSON.parseObject(newFeign.getCommunityList(param),ResponseData.class);
            ResponseData responseData = JSON.parseObject(newFeign.getList(),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                List<CommunityDTO> communityDTO = JSON.parseArray(responseData.getData().toString(),CommunityDTO.class);
                communityMap = communityDTO.stream().collect(Collectors.toMap(CommunityDTO::getId, CommunityDTO::getCommunityName));
            }
        }
        List<SysUserVO> voList = SysUserConvert.INSTANCE.convertList(list);
        if(!ObjectUtils.isEmpty(voList)){
            Map<String, String> finalCommunityMap = communityMap;
            voList.forEach(t->{
                t.setCommunityName(finalCommunityMap.get(t.getCommunityId()));
            });
        }
        return new PageResult<>(voList, page.getTotal());
    }

    private Map<String, Object> getParams(SysUserQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", query.getUsername());
        params.put("mobile", query.getMobile());
        params.put("gender", query.getGender());
        params.put("orgIds", query.getOrgIds());
        params.put("merchantId", query.getMerchantId());
        params.put("userType",query.getUserType());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"sys_user"));

        return params;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserVO vo) {


        SysUser entity = SysUserConvert.INSTANCE.convert(vo);

        if(ObjectUtils.isEmpty(vo.getSuperAdmin())){
            entity.setSuperAdmin(SuperAdminEnum.NO.getValue());
        }

        /*if(ObjectUtils.isEmpty(vo.getMerchantId())){
            entity.setMerchantId(SecurityUser.getUser().getMerchantId());
        }*/

        if(ObjectUtils.isEmpty(vo.getUserType())){
            entity.setUserType(1);
            // 判断用户名是否存在
            SysUser user = baseMapper.getByUsername(entity.getUsername(),null,null);
            if (user != null) {
                throw new ServerException("用户名已经存在");
            }

            // 判断手机号是否存在
            user = baseMapper.getByMobile(entity.getMobile(),null);
            if (user != null) {
                throw new ServerException("手机号已经存在");
            }
        }else{
            // 判断用户名是否存在
            SysUser user = baseMapper.getByUsername(entity.getUsername(),entity.getMerchantId(),entity.getCommunityId());
            if (user != null) {
                throw new ServerException("用户名已经存在");
            }

            // 判断手机号是否存在
            user = baseMapper.getByMobile(entity.getMobile(),entity.getCommunityId());
            if (user != null) {
                throw new ServerException("手机号已经存在");
            }
        }
        entity.setStatus(1);

        // 保存用户
        baseMapper.insert(entity);

        if(!ObjectUtils.isEmpty(vo.getUserType())&&vo.getUserType().equals(2)){

        }else {
            // 保存用户角色关系
            sysUserRoleService.saveOrUpdate(entity.getId(), vo.getRoleIdList());

            // 更新用户岗位关系
            sysUserPostService.saveOrUpdate(entity.getId(), vo.getPostIdList());
        }
    }

    @Override
    @Transactional
    public void update(SysUserVO vo) {
        SysUser entity = SysUserConvert.INSTANCE.convert(vo);

        if(!ObjectUtils.isEmpty(vo.getIdCard())){
            entity.setCardStatus(1);
        }

        if(ObjectUtils.isEmpty(vo.getMerchantId())){
            entity.setMerchantId(SecurityUser.getUser().getMerchantId());
        }
        // 判断用户名是否存在
        SysUser user = baseMapper.getByUsername(entity.getUsername(),entity.getMerchantId(),vo.getCommunityId());
        if (user != null && !user.getId().equals(entity.getId())) {
            throw new ServerException("用户名已经存在");
        }

        // 判断手机号是否存在
        user = baseMapper.getByMobile(entity.getMobile(),vo.getCommunityId());
        if (user != null && !user.getId().equals(entity.getId())) {
            throw new ServerException("手机号已经存在");
        }

        // 更新用户
        updateById(entity);

        if(!ObjectUtils.isEmpty(vo.getUserType())&&vo.getUserType().equals(2)){

        }else {
            // 更新用户角色关系
            sysUserRoleService.saveOrUpdate(entity.getId(), vo.getRoleIdList());

            // 更新用户岗位关系
            sysUserPostService.saveOrUpdate(entity.getId(), vo.getPostIdList());

        }

        // 更新用户缓存权限
        sysUserTokenService.updateCacheAuthByUserId(entity.getId());
    }

    @Override
    public void delete(List<String> idList) {
        // 删除用户
        removeByIds(idList);

        // 删除用户角色关系
        sysUserRoleService.deleteByUserIdList(idList);

        // 删除用户岗位关系
        sysUserPostService.deleteByUserIdList(idList);
    }

    @Override
    public SysUserVO getByMobile(String mobile,String communityId) {

        SysUser user = baseMapper.getByMobile(mobile,communityId);

        return SysUserConvert.INSTANCE.convert(user);
    }

    @Override
    public void updatePassword(String id, String newPassword) {
        // 修改密码
        SysUser user = getById(id);
        user.setPassword(newPassword);

        updateById(user);
    }

    @Override
    public PageResult<SysUserVO> roleUserPage(SysRoleUserQuery query) {
        // 查询参数
        Map<String, Object> params = getParams(query);
        params.put("roleId", query.getRoleId());

        // 分页查询
        IPage<SysUser> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<SysUser> list = baseMapper.getRoleUserList(params);

        return new PageResult<>(SysUserConvert.INSTANCE.convertList(list), page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importByExcel(MultipartFile file, String password) {

        ExcelUtils.readAnalysis(file, SysUserExcelVO.class, new ExcelFinishCallBack<SysUserExcelVO>() {
            @Override
            public void doAfterAllAnalysed(List<SysUserExcelVO> result) {
                saveUser(result);
            }

            @Override
            public void doSaveBatch(List<SysUserExcelVO> result) {
                saveUser(result);
            }

            private void saveUser(List<SysUserExcelVO> result) {
                ExcelUtils.parseDict(result);
                List<SysUser> sysUserEntities = SysUserConvert.INSTANCE.convertListEntity(result);
                sysUserEntities.forEach(user -> user.setPassword(password));
                saveBatch(sysUserEntities);
            }
        });

    }

    @Override
    @SneakyThrows
    public void export() {
        List<SysUser> list = list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getSuperAdmin, SuperAdminEnum.NO.getValue()));
        List<SysUserExcelVO> userExcelVOS = SysUserConvert.INSTANCE.convert2List(list);
        transService.transBatch(userExcelVOS);
        // 写到浏览器打开
        ExcelUtils.excelExport(SysUserExcelVO.class, "system_user_excel" + DateUtils.format(new Date()), null, userExcelVOS);
    }

    @Override
    public List<SysUser> userIdsList(UserParam userParam) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.in("id", userParam.getUserIds());
        return list(wrapper);
    }

    @Override
    public List<SysUserVO> allList() {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDeleted, 0);
        wrapper.eq(SysUser::getUserType,2);

        // 数据权限
        dataScopeWrapper(wrapper);

        List<SysUser> list = baseMapper.selectList(wrapper);

        return SysUserConvert.INSTANCE.convertList(list);
    }

    private Wrapper<SysUser> getWrapper(SysUserQuery query){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDeleted, 0);
        if (StringUtils.isNotBlank(query.getUsername())) {
            wrapper.like(SysUser::getUsername, query.getUsername());
        }
        if (StringUtils.isNotBlank(query.getMobile())) {
            wrapper.like(SysUser::getMobile, query.getMobile());
        }
        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }

}
